package com.tj.admin.auth.service;

import com.fqgj.common.api.Page;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.google.common.collect.Lists;
import com.qianli.cashmama.product.facade.ProductFacade;
import com.qianli.cashmama.product.facade.enums.PaybackPeriodUnitEnum;
import com.qianli.cashmama.product.facade.result.Product;
import com.qianli.cashmama.product.facade.result.ProductCategory;
import com.tj.admin.auth.request.AddProductRequest;
import com.tj.admin.auth.request.EditorProductRequest;
import com.tj.admin.auth.response.ProductListDTO;
import com.tj.admin.auth.vo.MerchantCode;
import com.tj.admin.auth.vo.ProductInfoVo;
import com.tj.admin.auth.vo.RequestLocalInfo;
import com.tj.admin.db.dao.AdminDao;
import com.tj.admin.db.dao.AdminTokenDao;
import com.tj.admin.db.entity.AdminEntity;
import com.tj.admin.db.entity.AdminTokenEntity;
import com.tj.bo.common.conf.api.ApiResponse;
import com.tj.bo.common.conf.enums.RestCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProductApplication {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProductApplication.class);


    @Autowired
    private ProductFacade productFacade;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private AdminTokenDao adminTokenDao;
    /**
     * @param page
     */
    public ApiResponse<ProductListDTO> queryProductList(Page page, String productName) {

        Response<List<ProductCategory>> allActiveProductCategory;
        List<Product> productList;
        if (StringUtils.isEmpty(productName)){
            String accessToken = RequestLocalInfo.getCurrentUser().getAccessToken();
            AdminTokenEntity adminTokenEntity = adminTokenDao.selectOnByAccessToken(accessToken);
            AdminEntity adminEntity = adminDao.select(new MerchantCode(adminTokenEntity.getMerchantCode()));
            String merchantCode = adminEntity.getMerchantCode();
            allActiveProductCategory  = productFacade.getProductCategoriesByMerchantCode(merchantCode);
            productList = productFacade.getProductByMerchantCode(merchantCode).getData();
        }else {
            allActiveProductCategory  = productFacade.getProductCategoriesByMerchantCode(productName);
            productList = productFacade.getProductByMerchantCode(productName).getData();
        }
        Product product = productList.get(0);

        ArrayList<ProductInfoVo> list = Lists.newArrayList();
        allActiveProductCategory.getData().forEach(item ->{
            ProductInfoVo productInfoVo = new ProductInfoVo();
            productInfoVo.setProductLogo(item.getLogo());
            productInfoVo.setProductDesc(item.getCategoryDesc());
            productInfoVo.setProductName(item.getName());
            productInfoVo.setMoneyFloor(item.getMoneyFloor());
            productInfoVo.setMoneyUpper(item.getMoneyUpper());
            list.add(productInfoVo);
        });
        ProductListDTO dto = new ProductListDTO(allActiveProductCategory.isEmpty() ? Lists.newArrayList() : list);
        page.setTotalPage(allActiveProductCategory.getData().size());

        return new ApiResponse(dto).setPage(page);
    }

    public void addProduct(AddProductRequest body){
        Response<ProductCategory> categoryByCode = productFacade.getCategoryByCode(body.getName());
        if (categoryByCode.getData() == null) {
            ProductCategory productCategory = new ProductCategory();
            productCategory.setLogo(body.getUrl());
            productCategory.setName(body.getName());
            productCategory.setCategoryDesc(body.getDesc());
            productCategory.setCode(body.getName());
            productCategory.setMoneyFloor(body.getMoneyFloor());
            productCategory.setMoneyUpper(body.getMoneyUpper());
            productCategory.setMerchantDoaminUrl(body.getMerchantDoaminUrl());
            productCategory.setEffectiveStartTime(new Date());
            productCategory.setEffectiveEndTime(DateUtil.addDate(new Date(), 360));
            productCategory.setIsSelling(0);
            PaybackPeriodUnitEnum paybackPeriodUnitEnum = PaybackPeriodUnitEnum.DAY;
            productCategory.setPaybackPeriodUnit(paybackPeriodUnitEnum.getCode());
            productCategory.setCategoryType(3);
            productCategory.setDailyApplyLimit(Integer.valueOf(body.getPutOnSize()));
//            productFacade.saveProductCategory(productCategory);
        }else {
            Response<List<Product>> productByMerchantCode = productFacade.getProductByMerchantCode(categoryByCode.getData().getMerchantCode());
            if (!productByMerchantCode.getData().isEmpty()){
                throw new RuntimeException(RestCodeEnum.OPERATION_FAILED.getDesc());
            }
            Product product = new Product();
            product.setCode(body.getName());
            product.setPrincipalMoney(body.getStartingAmount());
            int arrivalMoney = (int)(Double.parseDouble(body.getStartingAmount()) - Double.parseDouble(body.getStartingAmount()) * Double.parseDouble(body.getServiceFeeRate())/100d);
            product.setArrivalMoney(String.valueOf(arrivalMoney));
            product.setPaybackPeriodLength(Integer.parseInt(body.getStartingDays()));
            product.setTotalPaybackPeriodCount(1);
            product.setRate(body.getYearRate());
            product.setServiceFeeRate(body.getServiceFeeRate());
            product.setOverdueServiceCharge(body.getOverdueServiceCharge());
            product.setPenaltyRate(body.getPenaltyRate());
            product.setShowFlag("0");
            product.setLogo(body.getUrl());
            product.setProtocol(body.getProtocol());
//            product.setLoanUser(body.getLoanUser());
//            productFacade.saveProduct(product);
        }
    }

    public void editorProduct(EditorProductRequest request){

    }
}
